package com.dong.ch07_set;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class Solution350 {
    public int[] intersect(int[] nums1, int[] nums2) {
        Map<Integer, Integer> map = new HashMap<Integer,Integer>();
        for (int i = 0; i < nums1.length; i++) {
            if(map.containsKey(nums1[i])) {
                map.put(nums1[i],map.get(nums1[i])+1);
            }else {
                map.put(nums1[i],1);
            }
        }
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < nums2.length; i++) {
            if(map.containsKey(nums2[i])) {
                list.add(nums2[i]);
                int currentCount = map.get(nums2[i]) - 1;
                if(currentCount==0) {
                    map.remove(nums2[i]);
                }else {
                    map.put(nums2[i], currentCount);
                }
            }
        }
        int[] resultArr = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            resultArr[i]=list.get(i);
        }
        return resultArr;
    }
}
